//
//  LTDownloadOperation.m
//  Total
//
//  Created by xin on 2017/6/27.
//  Copyright © 2017年 elephants. All rights reserved.
//

#import "LTDownloadOperation.h"

@implementation LTDownloadOperation

- (id)initWithUrl:(NSString *)url delegate:(id<LTDownloadOperationDelegate>)delegate
{
    if (self = [super init]) {
        self.imageUrl = url;
        self.delegate = delegate;
    }
    return self;
}

- (void)dealloc
{
    self.imageUrl = nil;
    self.delegate = nil;
}

- (void)main
{
    //新建一个自动释放池，如果是异步操作，那么将无法访问到主线程的自动释放池
    @autoreleasepool {
        if (self.isCancelled) {
            return;
        }
        
        //获取图片数据
        NSURL * url = [NSURL URLWithString:self.imageUrl];
        NSData * imageData = [NSData dataWithContentsOfURL:url];
        
        if (self.isCancelled) {
            url = nil;
            imageData = nil;
            return;
        }
        
        //初始化图片
        UIImage *image = [UIImage imageWithData:imageData];
        
        if (self.isCancelled) {
            image = nil;
            return;
        }
        
        if ([self.delegate respondsToSelector:@selector(downloadFinishWithImage:)]) {
            //把图片数据传回主线程
            [(NSObject *)self.delegate performSelectorOnMainThread:@selector(downloadFinishWithImage:) withObject:image waitUntilDone:NO];
        }
    }
}

@end
